package com.dotnet.modules.price.controller;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dotnet.common.web.BaseController;
import com.dotnet.modules.price.entity.Price;
import com.dotnet.modules.price.service.PriceService;

/**
 * 
 * 描述：
 * 创建人： 魏泽超
 * 创建时间: 2016-6-21 上午9:47:15
 * @version
 */
@Controller
@RequestMapping("/price")
public class PriceController extends BaseController {

	@Autowired
	private PriceService priceService;

	/**
	 * 
	 * 描述：
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-21 下午2:40:26
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/getPrice")
	public Map<String, Object> getPrice(String productId, String json) {
		Map<String, Object> map = new HashMap<String, Object>();
		Price price = new Price();
		price.setProductId(Integer.valueOf(productId));
		price.setIsDelete(0);
		price.setIsUse(1);
		List<Price> queryAll = priceService.queryAll(price);
		if (null != queryAll && queryAll.size() > 0) {
			// json 跟 后台作比较，如果有则返回价格，没有则返回false
			String resultPrice=toMap(queryAll, json);
			if(StringUtils.isNotBlank(resultPrice)){
				map.put("status", true);
				map.put("price", resultPrice);
			}else{
				map.put("status", false);
				map.put("msg", "暂无对应价格，请填写管理员");
			}
		} else {
			map.put("status", false);
			map.put("msg", "暂无对应价格，请填写管理员");
		}
		return map;
	}

	/**  
	* 将json格式的字符串解析成Map对象 <li>  
	* json格式：{"name":"admin","retries":"3fff","testname"  
	* :"ddd","testretries":"fffffffff"}  
	*/
	private String toMap(List<Price> queryAll, String orderJson) {
		// JSON -> Map
		String getPrice = "";
		for (Price price : queryAll) {
			LinkedHashMap<String, Object> sqlMap = JSON.parseObject(price.getField(), new TypeReference<LinkedHashMap<String, Object>>() {
			});
			LinkedHashMap<String, Object> orderjson = JSON.parseObject(orderJson, new TypeReference<LinkedHashMap<String, Object>>() {
			});
			LinkedHashMap<String, Object> newJson = new LinkedHashMap<String, Object>();
			for (String key : sqlMap.keySet()) {
				if (key.equals("productId") || key.equals("productName") || key.equals("price")) {
					continue;
				} else {
					newJson.put(key, sqlMap.get(key));
				}
				if(newJson.equals(orderjson)){
					getPrice = price.getPrice().toString();
				}
			}
			//System.out.println(newJson);
			//System.out.println(orderjson);
		}
		System.out.println("价格为:"+getPrice);
		return getPrice;
	}
}
